const { User, ConsultationRoom, Appointment, sequelize } = require("../db");
const { Op, Sequelize } = require("sequelize");

// 检查时间段是否已被预约
async function isTimeSlotBooked(appointment_date, duration, excludeId = null) {
    const whereCondition = {
        appointment_date,
        [Op.or]: [
            { duration: { [Op.gte]: duration } },
            {
                [Op.and]: [
                    { appointment_date: { [Op.lte]: appointment_date } },
                    Sequelize.literal(`appointment_date + INTERVAL duration MINUTE >= '${appointment_date}'`)
                ]
            }
        ]
    };

    if (excludeId) {
        whereCondition.id = { [Op.ne]: excludeId };
    }

    const existingBooking = await ConsultationRoom.findOne({
        where: whereCondition
    });

    return !!existingBooking;
}

// 获取预约信息的接口
exports.getAppointmentInfo = async (req, res) => {
    const { 
        appointment_id, 
        user_id, 
        counselor_or_assistant_id,
        page = 1, 
        pageSize = 10 
    } = req.query;

    try {
        // 构建查询条件
        const whereCondition = {};
        const includeCondition = [
            {
                model: User,
                as: 'user',
                attributes: ['id', 'name', 'email', 'phone', 'is_counselor']
            },
            {
                model: User,
                as: 'counselorOrAssistant',
                attributes: ['id', 'name', 'email']
            }
        ];

        // 按预约ID查询
        if (appointment_id) {
            whereCondition.appointment_id = appointment_id;
        }

        // 按用户ID查询
        if (user_id) {
            whereCondition.user_id = user_id;
        }

        // 按咨询师或辅导员ID查询
        if (counselor_or_assistant_id) {
            whereCondition.counselor_or_assistant_id = counselor_or_assistant_id;
        }

        // 分页设置
        const offset = (page - 1) * pageSize;
        const limit = parseInt(pageSize);

        // 查询预约信息
        const { count, rows } = await Appointment.findAndCountAll({
            where: whereCondition,
            include: includeCondition,
            order: [['start_time', 'ASC']],
            offset,
            limit
        });

        // 格式化返回数据
        const formattedData = rows.map(appointment => ({
            id: appointment.appointment_id,
            user: appointment.user,
            counselorOrAssistant: appointment.counselorOrAssistant || null,
            appointments_phone: appointment.appointments_phone,
            room_number: appointment.room_number,
            start_time: appointment.start_time,
            end_time: appointment.end_time,
            status: appointment.status
        }));

        res.status(200).json({
            status: 200,
            message: '获取预约信息成功',
            data: {
                appointments: formattedData,
                pagination: {
                    total: count,
                    page: parseInt(page),
                    pageSize: parseInt(pageSize),
                    totalPages: Math.ceil(count / pageSize)
                }
            }
        });

    } catch (error) {
        console.error(error);
        res.status(500).json({
            status: 500,
            message: '获取预约信息失败',
            error: error.message
        });
    }
};

// 获取咨询室信息
exports.getConsultationRoomInfo = async (req, res) => {
    const { 
        room_id, 
        date, 
        start_date, 
        end_date, 
        user_id, 
        counselor_id,
        page = 1, 
        pageSize = 10 
    } = req.query;

    try {
        // 构建查询条件
        const whereCondition = {};
        const includeCondition = [{
            model: User,
            as: 'user',
            attributes: ['id', 'name', 'email', 'phone', 'is_counselor']
        }];
        
        // 按咨询室ID查询
        if (room_id) {
            whereCondition.id = room_id;
        }
        
        // 按用户ID查询
        if (user_id) {
            whereCondition.user_id = user_id;
        }
        
        // 按咨询师ID查询
        if (counselor_id) {
            includeCondition.push({
                model: User,
                as: 'counselor',
                where: { id: counselor_id },
                attributes: ['id', 'name', 'email']
            });
        }
        
        // 按具体日期查询
        if (date) {
            whereCondition.appointment_date = {
                [Op.between]: [
                    new Date(`${date}T00:00:00Z`),
                    new Date(`${date}T23:59:59Z`)
                ]
            };
        }
        
        // 按日期范围查询
        if (start_date && end_date) {
            whereCondition.appointment_date = {
                [Op.between]: [
                    new Date(`${start_date}T00:00:00Z`),
                    new Date(`${end_date}T23:59:59Z`)
                ]
            };
        }
        
        // 分页设置
        const offset = (page - 1) * pageSize;
        const limit = parseInt(pageSize);
        
        // 查询咨询室信息
        const { count, rows } = await ConsultationRoom.findAndCountAll({
            where: whereCondition,
            include: includeCondition,
            order: [['appointment_date', 'ASC']],
            offset,
            limit
        });
        
        // 格式化返回数据
        const formattedData = rows.map(room => ({
            id: room.id,
            reason: room.reason,
            appointment_date: room.appointment_date,
            duration: room.duration,
            created_at: room.created_at,
            user: room.user,
            counselor: room.counselor || null,
            status: calculateBookingStatus(room.appointment_date, room.duration)
        }));
        
        res.status(200).json({
            status: 200,
            message: '获取咨询室信息成功',
            data: {
                rooms: formattedData,
                pagination: {
                    total: count,
                    page: parseInt(page),
                    pageSize: parseInt(pageSize),
                    totalPages: Math.ceil(count / pageSize)
                }
            }
        });
        
    } catch (error) {
        console.error(error);
        res.status(500).json({
            status: 500,
            message: '获取咨询室信息失败',
            error: error.message
        });
    }
};

// 辅助函数：计算预约状态
function calculateBookingStatus(appointmentDate, duration) {
    const now = new Date();
    const startTime = new Date(appointmentDate);
    const endTime = new Date(startTime.getTime() + duration * 60000);
    
    if (now < startTime) {
        return 'pending'; // 未开始
    } else if (now >= startTime && now <= endTime) {
        return 'in_progress'; // 进行中
    } else {
        return 'completed'; // 已完成
    }
}

// 获取咨询师的空闲时间
exports.getCounselorFreeTime = async (req, res) => {
    const { counselor_id } = req.body;
    try {
        // 使用 findByPk 方法从数据库中获取咨询师信息
        const counselor = await User.findByPk(counselor_id);
        // 检查咨询师是否存在并且是咨询师（is_counselor 为 true）
        if (!counselor || counselor.is_counselor === false) {
            return res.status(404).json({
                status: 404,
                message: '指定的咨询师不存在'
            });
        }

        // 获取咨询师的空闲时间字段
        const counselorFreeTime = counselor.counselor_free_time;
        let parsedFreeTime;
        try {
            if (typeof counselorFreeTime === 'string') {
                parsedFreeTime = JSON.parse(counselorFreeTime);
            } else if (typeof counselorFreeTime === 'object' && counselorFreeTime !== null) {
                parsedFreeTime = counselorFreeTime;
            } else {
                parsedFreeTime = [];
            }
        } catch (error) {
            parsedFreeTime = [];
        }
        res.status(200).json({
            status: 200,
            message: '获取咨询师空闲时间成功',
            data: Array.isArray(parsedFreeTime) ? parsedFreeTime : []
        });
    } catch (error) {
        console.error(error);
        res.status(500).json({
            status: 500,
            message: '获取咨询师空闲时间失败'
        });
    }
};

// 预约咨询室 (所有人可预约，需填写时间和预约原因)
exports.bookConsultationRoom = async (req, res) => {
    const { reason, user_id, appointment_date, duration, counselor_or_assistant_id, appointments_phone } = req.body;

    // 检查是否填写了预约原因和时间等必要信息
    if (!reason ||!appointment_date ||!duration ||!counselor_or_assistant_id) {
        return res.status(400).json({
            status: 400,
            message: '预约时需要填写时间、预约原因和咨询师ID'
        });
    }

    try {
        // 检查用户是否存在
        const user = await User.findByPk(user_id);
        if (!user) {
            return res.status(404).json({
                status: 404,
                message: '用户不存在'
            });
        }

        // 获取指定的咨询师
        const counselor = await User.findByPk(counselor_or_assistant_id);
        if (!counselor || counselor.is_counselor === false) {
            return res.status(404).json({
                status: 404,
                message: '指定的咨询师不存在或不是咨询师'
            });
        }

        const counselorFreeTime = counselor.counselor_free_time;
        let parsedFreeTime;
        try {
            if (typeof counselorFreeTime === 'string') {
                parsedFreeTime = JSON.parse(counselorFreeTime);
            } else if (typeof counselorFreeTime === 'object' && counselorFreeTime !== null) {
                parsedFreeTime = counselorFreeTime;
            } else {
                parsedFreeTime = [];
            }
        } catch (error) {
            parsedFreeTime = [];
        }

        // 兼容数组格式校验空闲时间
        const appointmentDate = new Date(appointment_date).toISOString().split('T')[0];
        const appointmentTime = appointment_date.split('T')[1].slice(0, 5); // '09:00'
        const durationHours = duration / 60;
        const [startHour, startMin] = appointmentTime.split(':');
        const endHour = String(Number(startHour) + durationHours).padStart(2, '0');
        const endTime = `${endHour}:${startMin}`;
        const timeSlotStr = `${appointmentTime}-${endTime}`;

        let freeTimeSlots = [];
        if (Array.isArray(parsedFreeTime)) {
            const freeDay = parsedFreeTime.find(item => item.date === appointmentDate);
            freeTimeSlots = freeDay ? freeDay.time_slots : [];
        }
        const isInFreeTime = freeTimeSlots.includes(timeSlotStr);

        if (!isInFreeTime) {
            return res.status(400).json({
                status: 400,
                message: '预约时间不在咨询师的空闲时间内',
                availableTimes: freeTimeSlots
            });
        }

        // 检查咨询室在该时间段是否已被预约
        // 这里假设 isTimeSlotBooked 函数是一个已定义的函数，用于检查时间槽是否已被预约
        const isRoomBooked = await isTimeSlotBooked(appointment_date, duration);
        if (isRoomBooked) {
            return res.status(400).json({
                status: 400,
                message: '该咨询室在所选时间段已被预约'
            });
        }

        // 选择的咨询师在该时间段有空，进行预约，向咨询室表插入记录
        const booking = await ConsultationRoom.create({
            reason,
            user_id,
            appointment_date,
            duration,
            counselor_or_assistant_id: counselor.id
        });

        // 创建预约信息表（Appointment 表）的记录，添加 appointments_phone 字段
        const appointmentStart = new Date(appointment_date);
        const appointmentEnd = new Date(appointmentStart.getTime() + duration * 60000);
        await Appointment.create({
            user_id,
            counselor_or_assistant_id: counselor.id,
            appointments_phone, // 添加手机号
            // 这里只是简单示例，实际需要根据逻辑获取房间号
            room_number: '101', 
            start_time: appointmentStart,
            end_time: appointmentEnd,
            status: 'pending'
        });

        res.status(201).json({
            status: 201,
            message: '咨询预约成功',
            data: booking,
            availableTimes: freeTimeSlots
        });
    } catch (error) {
        console.error(error);
        res.status(500).json({
            status: 500,
            message: '咨询预约失败'
        });
    }
};

// 更新咨询室预约 (用户可修改自己或符合权限的预约)
exports.updateConsultationRoom = async (req, res) => {
    const { id } = req.body;
    const { reason, appointment_date, duration, user_id, appointments_phone } = req.body;

    try {
        // 检查预约是否存在
        const booking = await ConsultationRoom.findByPk(id);
        if (!booking) {
            return res.status(404).json({
                status: 404,
                message: '未找到指定的咨询室预约'
            });
        }

        // 检查用户权限
        const user = await User.findByPk(user_id);
        if (!user) {
            return res.status(404).json({
                status: 404,
                message: '用户不存在'
            });
        }

        // 用户可以修改自己的预约，辅导员和管理员还能修改他人预约
        if (!user.is_admin &&!user.is_assistant &&!user.is_counselor && booking.user_id!== user_id) {
            return res.status(403).json({
                status: 403,
                message: '无权修改此预约'
            });
        }

        // 检查时间段是否已被其他人预约
        if (appointment_date && duration) {
            const isBooked = await isTimeSlotBooked(appointment_date, duration, id);
            if (isBooked) {
                return res.status(400).json({
                    status: 400,
                    message: '该时间段已被预约'
                });
            }
        }

        const [updated] = await ConsultationRoom.update({
            reason,
            appointment_date,
            duration
        }, {
            where: { id }
        });

        if (updated) {
            // 更新 Appointment 表中的手机号
            await Appointment.update({
                appointments_phone
            }, {
                where: {
                    user_id,
                    counselor_or_assistant_id: booking.counselor_or_assistant_id,
                    start_time: new Date(booking.appointment_date),
                    end_time: new Date(new Date(booking.appointment_date).getTime() + booking.duration * 60000)
                }
            });

            res.status(200).json({
                status: 200,
                message: '咨询室预约更新成功'
            });
        } else {
            res.status(404).json({
                status: 404,
                message: '未找到指定的咨询室预约'
            });
        }
    } catch (error) {
        console.error(error);
        res.status(500).json({
            status: 500,
            message: '更新咨询室预约失败'
        });
    }
};

// 取消咨询室预约 (辅导员/管理员可取消任何预约，普通用户和咨询师只能取消自己的)
exports.cancelConsultationRoom = async (req, res) => {
    const { id } = req.body;
    const { user_id } = req.body;

    try {
        const booking = await ConsultationRoom.findByPk(id, {
            include: [{
                model: User,
                as: 'user',
                attributes: ['id', 'username', 'name', 'email']
            }]
        });
        
        if (!booking) {
            return res.status(404).json({
                status: 404,
                message: '未找到指定的咨询室预约'
            });
        }

        // 检查用户权限
        const currentUser = await User.findByPk(user_id);
        if (!currentUser) {
            return res.status(404).json({
                status: 404,
                message: '用户不存在'
            });
        }

        // 管理员和辅导员可以取消任何预约，其他用户只能取消自己的预约
        if (!currentUser.is_admin && !currentUser.is_assistantn && booking.user_id !== user_id) {
            return res.status(403).json({
                status: 403,
                message: '无权取消此预约'
            });
        }

        // 获取相关咨询师信息（假设咨询师是预约的用户或另有字段指定）
        const counselor = await User.findOne({
            where: { 
                is_counselor: true,
                // 这里假设咨询师是通过某种方式关联的，根据实际业务调整
                id: booking.user_id // 或其他关联字段
            }
        });

        // 删除预约
        const deleted = await ConsultationRoom.destroy({
            where: { id }
        });

        if (deleted) {
            // 如果是管理员或辅导员取消的，发送通知给预约用户和咨询师
            if (currentUser.is_admin || currentUser.is_assistantn) {
                // 给预约用户发送通知
                if (booking.user && booking.user.id !== currentUser.id) {
                    await Notification.create({
                        user_id: booking.user.id,
                        sender_id: currentUser.id,
                        content: `您的预约已被${currentUser.is_admin ? '管理员' : '辅导员'}取消`,
                        type: 'cancel_booking',
                        booking_id: id
                    });
                    
                    // 这里可以添加邮件或短信通知逻辑
                    // sendEmail(booking.user.email, '预约取消通知', `您的预约已被${currentUser.is_admin ? '管理员' : '辅导员'}取消`);
                }

                // 给咨询师发送通知（如果存在且不是取消者本人）
                if (counselor && counselor.id !== currentUser.id) {
                    await Notification.create({
                        user_id: counselor.id,
                        sender_id: currentUser.id,
                        content: `您的一个咨询预约已被${currentUser.is_admin ? '管理员' : '辅导员'}取消`,
                        type: 'cancel_booking',
                        booking_id: id
                    });
                    
                    // 这里可以添加邮件或短信通知逻辑
                    // sendEmail(counselor.email, '预约取消通知', `您的一个咨询预约已被${currentUser.is_admin ? '管理员' : '辅导员'}取消`);
                }
            }

            res.status(200).json({
                status: 200,
                message: '咨询室预约取消成功',
                data: {
                    notified_users: [
                        booking.user ? { id: booking.user.id, name: booking.user.name } : null,
                        counselor ? { id: counselor.id, name: counselor.name } : null
                    ].filter(u => u)
                }
            });
        } else {
            res.status(404).json({
                status: 404,
                message:'未找到指定的咨询室预约'
            });
        }
    } catch (error) {
        console.error(error);
        res.status(500).json({
            status: 500,
            message: '取消咨询室预约失败',
            error: error.message
        });
    }
};

// 获取用户通知
exports.getUserNotifications = async (req, res) => {
    const { user_id } = req.body;
    const { page = 1, pageSize = 10, unread_only = false } = req.query;

    try {
        const whereCondition = { user_id };
        if (unread_only === 'true') {
            whereCondition.is_read = false;
        }

        const notifications = await Notification.findAndCountAll({
            where: whereCondition,
            include: [{
                model: User,
                as:'sender',
                attributes: ['id', 'name', 'avatar']
            }],
            order: [['created_at', 'DESC']],
            offset: (page - 1) * pageSize,
            limit: parseInt(pageSize)
        });

        res.status(200).json({
            status: 200,
            message: '获取通知成功',
            data: {
                notifications: notifications.rows,
                total: notifications.count,
                page: parseInt(page),
                pageSize: parseInt(pageSize),
                totalPages: Math.ceil(notifications.count / pageSize)
            }
        });
    } catch (error) {
        console.error(error);
        res.status(500).json({
            status: 500,
            message: '获取通知失败',
            error: error.message
        });
    }
};

// 标记通知为已读
exports.markNotificationAsRead = async (req, res) => {
    const { notification_id } = req.body;

    try {
        const [updated] = await Notification.update(
            { is_read: true },
            { where: { id: notification_id } }
        );

        if (updated) {
            res.status(200).json({
                status: 200,
                message: '通知已标记为已读'
            });
        } else {
            res.status(404).json({
                status: 404,
                message: '未找到指定的通知'
            });
        }
    } catch (error) {
        console.error(error);
        res.status(500).json({
            status: 500,
            message: '标记通知为已读失败',
            error: error.message
        });
    }
};
